$(function () {
  if (!localStorage.getItem("token")) {
    layui.layer.msg("登录失败，token缺失", { icon: 5 }, function () {
      localStorage.removeItem("token");
      // 2. 强制跳转到登录页面
      window.parent.location.href = "/bigevent-end/login.html";
    });
  }
  load();

  function load() {
    $.ajax({
      url: "/admin/swipers",
      method: "get",
      success: function (res) {
        if (res.status !== 0) {
          return layui.layer.msg(res.message, { icon: 5 });
        }
        var html = template("tpl", res);
        $("tbody").html(html);
      },
    });
  }

  $("tbody").on("click", "span", function () {
    let id = $(this).attr("data-id");
    let status = $(this).attr("data-status");
    $.ajax({
      url: "/admin/swipers/" + id,
      method: "put",
      data: {
        status,
      },
      success: function (res) {
        if (res.status !== 0) {
          return layui.layer.msg(res.message, { icon: 5 });
        }
        layui.layer.msg('"切换状态成功"', { icon: 6 });
        load();
      },
    });
  });

  $("tbody").on("click", "button", function () {
    let id = $(this).attr("data-id");
    layui.layer.confirm("是否删除？", { icon: 3, title: "提示" }, function (index) {
      if ($("tbody").children().length > 1) {
        $.ajax({
          url: "/admin/swipers/" + id,
          method: "delete",
          success: function (res) {
            if (res.status !== 0) {
              return layui.layer.msg(res.message, { icon: 5 });
            }
            layui.layer.msg("删除成功", { icon: 6 });
            load();
          },
        });
      } else {
        layui.layer.msg("轮播图长度为1", { icon: 5 });
      }

      layer.close(index);
    });
  });

  $("#uploadSwiper").on("click", function () {
    $("#myfile").click();
  });

  $("#myfile").on("change", function () {
    var file = $(this)[0].files;
    if (file.length === 0) layui.layer.msg("请选择文件");
    var fd = new FormData();
    if (file.length === 1) {
      fd.append("swipers", file[0]);
    } else {
      for (var i = 0; i < file.length; i++) {
        fd.append("swipers", file[i]);
      }
    }

    $.ajax({
      url: "/admin/swipers",
      method: "post",
      data: fd,
      contentType: false,
      processData: false,
      success: function (res) {
        if (res.status !== 0) {
          return layui.layer.msg(res.message, { icon: 5 });
        }
        layui.layer.msg("上传成功", { icon: 6 });
        load();
      },
    });
  });
});
